﻿
Imports System.Runtime.CompilerServices
Imports System.Text
Imports osi.root.constants

Public Module _character
    Private ReadOnly utf8() As Boolean

    Sub New()
        ReDim utf8(Convert.ToInt32(Char.MaxValue) - Convert.ToInt32(Char.MinValue))

        For i As Int32 = Convert.ToInt32(Char.MinValue) To Convert.ToInt32(Char.MaxValue)
            utf8(i - Convert.ToInt32(Char.MinValue)) =
                (Encoding.UTF8().GetChars(Encoding.UTF8().GetBytes(Convert.ToChar(i)))(0) = Convert.ToChar(i))
        Next
    End Sub

    <Extension()> Public Function lowalpha(ByVal c As Char) As Boolean
        Return (c >= character.a AndAlso c <= character.z)
    End Function

    <Extension()> Public Function hialpha(ByVal c As Char) As Boolean
        Return (c >= character._A AndAlso c <= character._Z)
    End Function

    <Extension()> Public Function alpha(ByVal c As Char) As Boolean
        Return lowalpha(c) OrElse hialpha(c)
    End Function

    <Extension()> Public Function digit(ByVal c As Char) As Boolean
        Return c >= character._0 AndAlso c <= character._9
    End Function

    <Extension()> Public Function hex(ByVal c As Char) As Boolean
        Return digit(c) OrElse
               (c >= character.a AndAlso c <= character.f) OrElse
               (c >= character._A AndAlso c <= character._F)
    End Function

    <Extension()> Public Function hex_value(ByVal c As Char, ByRef v As Byte) As Boolean
        If hex(c) Then
            v = If(digit(c),
                   Convert.ToInt32(c) - Convert.ToInt32(character._0),
                   If(lowalpha(c),
                      Convert.ToInt32(c) - Convert.ToInt32(character.a),
                      Convert.ToInt32(c) - Convert.ToInt32(character._A)) + 10)
            Return True
        Else
            Return False
        End If
    End Function

    <Extension()> Public Function hex_value(ByVal c As Char) As Byte
        Dim v As Byte = 0
        k_assert(hex_value(c, v))
        Return v
    End Function

    <Extension()> Public Function utf8_supported(ByVal c As Char) As Boolean
        Return utf8(Convert.ToInt32(c) - Convert.ToInt32(Char.MinValue))
    End Function

    <Extension()> Public Function space(ByVal c As Char) As Boolean
        Return Char.IsWhiteSpace(c)
    End Function

    <Extension()> Public Function visible(ByVal c As Char) As Boolean
        Return Not Char.IsControl(c)
    End Function
End Module
